# -*- coding: utf-8 -*-

from server.models import db
from server.models import ObjectId


'''
数据库结构
    { "_id" : , 
      "name": ,
      "version": ,
      "project": ,
      "createDate": ,
      "creator": ,
      "equipmentList": ,
      "describe": 
     }
'''


class configurationDao(object):

    # 初始化变量
    def __init__(self):
        self._collection = db.configurationTable

    # 查找所有数据
    def select_configurations(self, condition, limit):
        if not isinstance(condition, dict):
            return None

        count = self._collection.find(condition).count()
        if count == 0:
            return count, []

        configurations = []

        for configurationInfo in self._collection.find(condition):
            configurationInfo['id'] = str(configurationInfo['_id'])
            configurationInfo.pop('_id')
            configurations.append(configurationInfo)

        return count, configurations[(limit['page'] - 1) * int(limit['limit']):
                                     (limit['page'] - 1) * int(limit['limit']) + limit['limit']]

    # 新建数据
    def add_configuration(self, configuration):
        if not isinstance(configuration, dict):
            return False

        info = self._collection.find_one(
            {"name": configuration["name"], "version": configuration["version"], "creator": configuration["creator"]})
        if info is not None:
            return False

        self._collection.insert_one(configuration)
        return True

    # 修改数据
    def update_configuration(self, configuration):
        if not isinstance(configuration, dict):
            return False

        updateInfo = self._collection.find_one({"_id": ObjectId(configuration["id"])})
        if updateInfo is None:
            return False

        for key in configuration:
            updateInfo[key] = configuration[key]

        self._collection.insert_one(updateInfo)

        return True

    # 删除数据
    def delete_configuration(self, configuration):
        if not isinstance(configuration, dict):
            return False

        info = self._collection.find_one({"_id": ObjectId(configuration["id"])})
        if info is None:
            return False

        self._collection.delete_one({"_id": ObjectId(configuration["id"])})

        return True
